
<!DOCTYPE html>
<html lang="en">
    <!--百度统计-->
    <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b94bd2699a7baf9292dd9cf571f7fbb9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
    </script>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="keywords" content="Python,Django,Python教程,Django教程,教程,基础教程,Web开发,运维,自动化,博客,编程,软件,云计算,大数据,爬虫,
    人工智能,机器学习,神经网络" />
    <meta name="description" content="提供Python和Django的原创中文精品教程和博客,分享技术知识,传播新闻视点,提倡开源精神,让更多开发者从中受益。">
    <meta name="author" content="刘江,liujiang,大江东流">
    <title>
    
    django Part 4：表单和类视图 - 刘江的django教程
    
</title>
	
	<!-- core CSS -->
    <link href="static/bootstrap.min.css" rel="stylesheet">
    <link href="static/font-awesome.min.css" rel="stylesheet">


    <link href="static/main.css" rel="stylesheet">

    <link href="static/github.css" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
    <script src="js/respond.min.js"></script>
    <![endif]-->       
    <link rel="shortcut icon" href="/static/images/ico/favicon.ico">
    
    <link href="static/course.css" rel="stylesheet">


</head><!--/head-->

<body class="homepage">

    <header id="header" class=" navbar-fixed-top">
        <div class="top-bar">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-6">
                        <div class="top-number">
                            <p><i class="fa fa-feed" aria-hidden="true"></i>&nbsp;
                            <strong style="color: red;">强烈推荐博主精心录制的Python及Django视频教程,<a href="/video/">详情点击</a>!</strong>
                            </p></div>
                    </div>
                    <div class="col-md-offset-3 col-md-3">
                        <span class="pull-left">分享：</span>
                        <!-- JiaThis Button BEGIN社会化分享工具 -->
                        <div class="jiathis_style_24x24">
                            <a class="jiathis_button_qzone"></a>
                            <a class="jiathis_button_tsina"></a>
                            <a class="jiathis_button_tqq"></a>
                            <a class="jiathis_button_weixin"></a>
                            <a class="jiathis_button_renren"></a>
                            <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
                        </div>

                        <!-- JiaThis Button END -->
                    </div>
                </div>
            </div><!--/.container-->
        </div><!--/.top-bar-->

		<nav class="navbar navbar-default navbar-inverse">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#my-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">刘江的博客及教程</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="my-navbar">
      <ul class="nav navbar-nav">
        <li><a href="/news/">新闻</a></li>
        <li><a href="/blog/">博客</a></li>
        <li><a href="/course/python/1">Python教程</a></li>
        <li><a href="2.html">Django教程</a></li>
        <li><a href="/video/">视频教程</a>
        <span class="badge" style="color: red;text-shadow:-1px 0 white,0 1px white,1px 0 white,0 -1px white; float: right;font-size: small;margin-left: -8px;">Hot!</span>
        </li>
      </ul>

      <form id="search-form" method="get" action="/blog/search/" class="navbar-form navbar-left collasped">
        <div class="form-group">
          <input type="text" name="keyword" class="form-control" placeholder="Search" required>
        </div>
        <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
      </form>

      <ul class="nav navbar-nav navbar-right">
          <li>
            
              <!--通过在login后添加next参数，让用户登录后返回先前的页面-->
            <a href="90.html">
            <span class="glyphicon glyphicon-log-in"></span>登录</a></li>
            
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

    </header><!--/header-->


    
    <div class="container-fluid main">
      <div class="row">

        <!-- 左侧目录栏 -->
        <div class="col-md-3">
          <div class="navbar-sider list-group-item">
            目&nbsp;录
            <hr />
            
                
                        
                            
                            <a href="2.html" class="list-group-item"><b>Django教程</b></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="84.html"
                               class="list-group-item"><strong>Django简介</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="85.html"
                               class="list-group-item"><strong>Django环境安装</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="86.html"
                               class="list-group-item"><strong>第一个Django应用</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="87.html"
                               class="list-group-item">Part 1：请求与响应</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="88.html"
                               class="list-group-item">Part 2：模型与管理后台</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="89.html"
                               class="list-group-item">Part 3：视图和模板</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="90.html"
                               class="list-group-item active">Part 4：表单和类视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="91.html"
                               class="list-group-item">Part 5：测试</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="92.html"
                               class="list-group-item">Part 6：静态文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="93.html"
                               class="list-group-item">Part 7：自定义admin站点</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="94.html"
                               class="list-group-item"><strong>第一章：模型层model layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="95.html"
                               class="list-group-item">模型和字段</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="96.html"
                               class="list-group-item">关系类型字段</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="97.html"
                               class="list-group-item">字段的参数</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="98.html"
                               class="list-group-item">多对多中间表详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="99.html"
                               class="list-group-item">模型的元数据Meta</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="100.html"
                               class="list-group-item">模型的继承</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="101.html"
                               class="list-group-item">用包来组织模型</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="129.html"
                               class="list-group-item">查询操作</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="130.html"
                               class="list-group-item">查询集API</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="131.html"
                               class="list-group-item">不返回QuerySets的API</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="132.html"
                               class="list-group-item">字段查询参数及聚合函数</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="133.html"
                               class="list-group-item"><strong>第二章：视图层view layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="182.html"
                               class="list-group-item">Django2.0 URL配置</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="134.html"
                               class="list-group-item">URL路由基础</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="135.html"
                               class="list-group-item">路由转发</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="136.html"
                               class="list-group-item">URL反向解析和命名空间</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="137.html"
                               class="list-group-item">视图函数及快捷方式</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="138.html"
                               class="list-group-item">HttpRequest对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="139.html"
                               class="list-group-item">QueryDict对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="140.html"
                               class="list-group-item">HttpResponse对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="141.html"
                               class="list-group-item">文件上传</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="142.html"
                               class="list-group-item">动态生成CSV文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="143.html"
                               class="list-group-item">动态生成PDF文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="144.html"
                               class="list-group-item"><strong>第三章：模版层Template layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="145.html"
                               class="list-group-item">Django模板语言详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="146.html"
                               class="list-group-item">Django内置模板标签</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="147.html"
                               class="list-group-item">Django内置模版过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="148.html"
                               class="list-group-item">特殊的标签和过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="149.html"
                               class="list-group-item">人类可读性</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="150.html"
                               class="list-group-item">自定义模板标签和过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="151.html"
                               class="list-group-item"><strong>第四章：Django表单</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="152.html"
                               class="list-group-item">使用表单</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="153.html"
                               class="list-group-item">Django表单API详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="154.html"
                               class="list-group-item">Django表单字段汇总</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="155.html"
                               class="list-group-item">表单的Widgets</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="156.html"
                               class="list-group-item">模型表单ModelForm</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="157.html"
                               class="list-group-item"><strong>第五章：Admin管理后台</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="158.html"
                               class="list-group-item">自定制Admin</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="159.html"
                               class="list-group-item">自定义Admin actions</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="160.html"
                               class="list-group-item">Admin文档生成器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="162.html"
                               class="list-group-item"><strong>第六章：Django 综合篇</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="163.html"
                               class="list-group-item">配置 Django</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="164.html"
                               class="list-group-item">核心配置项</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="165.html"
                               class="list-group-item">使用MySQL数据库</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="166.html"
                               class="list-group-item">django-admin和manage.py</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="167.html"
                               class="list-group-item">自定义django-admin命令</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="168.html"
                               class="list-group-item">会话session</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="169.html"
                               class="list-group-item">网站地图sitemap</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="170.html"
                               class="list-group-item">信号 signal</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="171.html"
                               class="list-group-item">序列化 serializers</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="172.html"
                               class="list-group-item">消息框架 message</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="173.html"
                               class="list-group-item">分页 Paginator</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="174.html"
                               class="list-group-item">聚合内容 RSS/Atom</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="175.html"
                               class="list-group-item">发送邮件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="176.html"
                               class="list-group-item">Django 日志</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="177.html"
                               class="list-group-item">Django与缓存</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="178.html"
                               class="list-group-item">认证系统 Authentication</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="179.html"
                               class="list-group-item">Django与CSRF 、AJAX</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="180.html"
                               class="list-group-item">Django 国际化和本地化</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="181.html"
                               class="list-group-item">部署 Django</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="102.html"
                               class="list-group-item"><strong>实战一：用户登录与注册系统</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="103.html"
                               class="list-group-item">1. 搭建项目环境</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="104.html"
                               class="list-group-item">2. 设计数据模型</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="105.html"
                               class="list-group-item">3. admin后台</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="106.html"
                               class="list-group-item">4. url路由和视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="107.html"
                               class="list-group-item">5. 前端页面设计</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="108.html"
                               class="list-group-item">6. 登录视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="109.html"
                               class="list-group-item">7. Django表单</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="110.html"
                               class="list-group-item">8. 图片验证码</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="111.html"
                               class="list-group-item">9. session会话</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="112.html"
                               class="list-group-item">10. 注册视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="113.html"
                               class="list-group-item">11.使用Django发送邮件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="114.html"
                               class="list-group-item">12. 邮件注册确认</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="115.html"
                               class="list-group-item">13. 使用Github管理项目</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="116.html"
                               class="list-group-item"><strong>实战二：CMDB之资产管理系统</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="117.html"
                               class="list-group-item">1.项目需求分析</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="118.html"
                               class="list-group-item">2.模型设计</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="119.html"
                               class="list-group-item">3.数据收集客户端</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="120.html"
                               class="list-group-item">4.Windows下收集数据</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="121.html"
                               class="list-group-item">5.Linux下收集数据</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="122.html"
                               class="list-group-item">6.新资产待审批区</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="123.html"
                               class="list-group-item">7.审批新资产</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="124.html"
                               class="list-group-item">8.已上线资产信息更新</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="125.html"
                               class="list-group-item">9.前端框架AdminLTE</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="126.html"
                               class="list-group-item">10.资产总表</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="127.html"
                               class="list-group-item">11.资产详细页面</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="128.html"
                               class="list-group-item">12.dashboard仪表盘</a>
                            
                        
                
            
          </div>
        </div>
        <!-- 左侧目录栏 结束 -->

        <!-- 右侧正文栏 -->
        <div class="col-md-9">
            <!-- 教程正文主体部分 -->
            <div class="row">
                <h1>Part 4：表单和类视图</h1>
                <p>阅读:&nbsp;5641</p>
                <hr/>
                <h2 id="form">一、表单form</h2>
<p>为了接收用户的投票选择，我们需要在前端页面显示一个投票界面。让我们重写先前的<code>polls/detail.html</code>文件，代码如下：</p>
<div class="codehilite"><pre><span></span><span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>{{ question.question_text }}<span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;</span>

{% if error_message %}<span class="p">&lt;</span><span class="nt">p</span><span class="p">&gt;&lt;</span><span class="nt">strong</span><span class="p">&gt;</span>{{ error_message }}<span class="p">&lt;/</span><span class="nt">strong</span><span class="p">&gt;&lt;/</span><span class="nt">p</span><span class="p">&gt;</span>{% endif %}

<span class="p">&lt;</span><span class="nt">form</span> <span class="na">action</span><span class="o">=</span><span class="s">&quot;{% url &#39;polls:vote&#39; question.id %}&quot;</span> <span class="na">method</span><span class="o">=</span><span class="s">&quot;post&quot;</span><span class="p">&gt;</span>
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <span class="p">&lt;</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">&quot;radio&quot;</span> <span class="na">name</span><span class="o">=</span><span class="s">&quot;choice&quot;</span> <span class="na">id</span><span class="o">=</span><span class="s">&quot;choice{{ forloop.counter }}&quot;</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;{{ choice.id }}&quot;</span> <span class="p">/&gt;</span>
    <span class="p">&lt;</span><span class="nt">label</span> <span class="na">for</span><span class="o">=</span><span class="s">&quot;choice{{ forloop.counter }}&quot;</span><span class="p">&gt;</span>{{ choice.choice_text }}<span class="p">&lt;/</span><span class="nt">label</span><span class="p">&gt;&lt;</span><span class="nt">br</span> <span class="p">/&gt;</span>
{% endfor %}
<span class="p">&lt;</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">&quot;submit&quot;</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;Vote&quot;</span> <span class="p">/&gt;</span>
<span class="p">&lt;/</span><span class="nt">form</span><span class="p">&gt;</span>
</pre></div>


<p>简要说明：</p>
<ul>
<li>上面的模板显示一系列单选按钮，按钮的值是选项的ID，按钮的名字是字符串"choice"。这意味着，当你选择了其中某个按钮，并提交表单，一个包含数据<code>choice=#</code>的POST请求将被发送到指定的url，<code>#</code>是被选择的选项的ID。这就是HTML表单的基本概念。</li>
<li>如果你有一定的前端开发基础，那么form标签的action属性和method属性你应该很清楚它们的含义，action表示你要发送的目的url，method表示提交数据的方式，一般分POST和GET。</li>
<li>forloop.counter是DJango模板系统专门提供的一个变量，用来表示你当前循环的次数，一般用来给循环项目添加有序数标。</li>
<li>由于我们发送了一个POST请求，就必须考虑一个跨站请求伪造的安全问题，简称CSRF（具体含义请百度）。Django为你提供了一个简单的方法来避免这个困扰，那就是在form表单内添加一条{% csrf_token %}标签，标签名不可更改，固定格式，位置任意，只要是在form表单内。这个方法对form表单的提交方式方便好使，但如果是用ajax的方式提交数据，那么就不能用这个方法了。</li>
</ul>
<p>现在，让我们创建一个处理提交过来的数据的视图。前面我们已经写了一个“占坑”的vote视图的url（polls/urls.py）：</p>
<div class="codehilite"><pre><span></span>url(r&#39;^(?P&lt;question_id&gt;[0-9]+)/vote/$&#39;, views.vote, name=&#39;vote&#39;),
</pre></div>


<p>以及“占坑”的vote视图函数（polls/views.py），我们把坑填起来：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">get_object_or_404</span><span class="p">,</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponseRedirect</span><span class="p">,</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">reverse</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Choice</span><span class="p">,</span> <span class="n">Question</span>
<span class="c1"># ...</span>

<span class="k">def</span> <span class="nf">vote</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">question_id</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">selected_choice</span> <span class="o">=</span> <span class="n">question</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s1">&#39;choice&#39;</span><span class="p">])</span>
    <span class="k">except</span> <span class="p">(</span><span class="ne">KeyError</span><span class="p">,</span> <span class="n">Choice</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">):</span>
        <span class="c1"># 发生choice未找到异常时，重新返回表单页面，并给出提示信息</span>
        <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/detail.html&#39;</span><span class="p">,</span> <span class="p">{</span>
        <span class="s1">&#39;question&#39;</span><span class="p">:</span> <span class="n">question</span><span class="p">,</span>
        <span class="s1">&#39;error_message&#39;</span><span class="p">:</span> <span class="s2">&quot;You didn&#39;t select a choice.&quot;</span><span class="p">,</span>
        <span class="p">})</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">selected_choice</span><span class="o">.</span><span class="n">votes</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="n">selected_choice</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
        <span class="c1"># 成功处理数据后，自动跳转到结果页面，防止用户连续多次提交。</span>
        <span class="k">return</span> <span class="n">HttpResponseRedirect</span><span class="p">(</span><span class="n">reverse</span><span class="p">(</span><span class="s1">&#39;polls:results&#39;</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">question</span><span class="o">.</span><span class="n">id</span><span class="p">,)))</span>
</pre></div>


<p>有些新的东西，我们要解释一下：</p>
<ul>
<li>request.POST是一个类似字典的对象，允许你通过键名访问提交的数据。本例中，<code>request.POST[’choice’]</code>返回被选择选项的ID，并且值的类型永远是string字符串，那怕它看起来像数字！同样的，你也可以用类似的手段获取GET请求发送过来的数据，一个道理。</li>
<li><code>request.POST[’choice’]</code>有可能触发一个KeyError异常，如果你的POST数据里没有提供choice键值，在这种情况下，上面的代码会返回表单页面并给出错误提示。PS：通常我们会给个默认值，防止这种异常的产生，例如<code>request.POST[’choice’,None]</code>，一个None解决所有问题。</li>
<li>在选择计数器加一后，返回的是一个<code>HttpResponseRedirect</code>而不是先前我们常用的<code>HttpResponse</code>。HttpResponseRedirect需要一个参数：重定向的URL。这里有一个建议，当你成功处理POST数据后，应当保持一个良好的习惯，始终返回一个HttpResponseRedirect。这不仅仅是对Django而言，它是一个良好的WEB开发习惯。</li>
<li>我们在上面HttpResponseRedirect的构造器中使用了一个<code>reverse()</code>函数。它能帮助我们避免在视图函数中硬编码URL。它首先需要一个我们在URLconf中指定的name，然后是传递的数据。例如<code>'/polls/3/results/'</code>，其中的3是某个<code>question.id</code>的值。重定向后将进入<code>polls:results</code>对应的视图，并将<code>question.id</code>传递给它。白话来讲，就是把活扔给另外一个路由对应的视图去干。</li>
</ul>
<p>当有人对某个问题投票后，vote()视图重定向到了问卷的结果显示页面。下面我们来写这个处理结果页面的视图(polls/views.py)：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">get_object_or_404</span><span class="p">,</span> <span class="n">render</span>

<span class="k">def</span> <span class="nf">results</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">question_id</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/results.html&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;question&#39;</span><span class="p">:</span> <span class="n">question</span><span class="p">})</span>
</pre></div>


<p>同样，还需要写个模板<code>polls/templates/polls/results.html</code>。（路由、视图、模板、模型！都是这个套路....）</p>
<div class="codehilite"><pre><span></span><span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>{{ question.question_text }}<span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">ul</span><span class="p">&gt;</span>
{% for choice in question.choice_set.all %}
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;</span>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}<span class="p">&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
{% endfor %}
<span class="p">&lt;/</span><span class="nt">ul</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">a</span> <span class="na">href</span><span class="o">=</span><span class="s">&quot;{% url &#39;polls:detail&#39; question.id %}&quot;</span><span class="p">&gt;</span>Vote again?<span class="p">&lt;/</span><span class="nt">a</span><span class="p">&gt;</span>
</pre></div>


<p>现在你可以到浏览器中访问<code>/polls/1/</code>了，投票吧。你会看到一个结果页面，每投一次，它的内容就更新一次。如果你提交的时候没有选择项目，则会得到一个错误提示。</p>
<p>如果你在前面漏掉了一部分操作没做，比如没有创建choice选项对象，那么可以按下面的操作，补充一下：</p>
<div class="codehilite"><pre><span></span><span class="n">F</span><span class="p">:</span>\<span class="n">Django_course</span>\<span class="n">mysite</span><span class="o">&gt;</span><span class="n">python</span> <span class="n">manage</span><span class="o">.</span><span class="n">py</span> <span class="n">shell</span>
<span class="n">Python</span> <span class="mf">3.6</span><span class="o">.</span><span class="mi">1</span> <span class="p">(</span><span class="n">v3</span><span class="o">.</span><span class="mf">6.1</span><span class="p">:</span><span class="mi">69</span><span class="n">c0db5</span><span class="p">,</span> <span class="n">Mar</span> <span class="mi">21</span> <span class="mi">2017</span><span class="p">,</span> <span class="mi">18</span><span class="p">:</span><span class="mi">41</span><span class="p">:</span><span class="mi">36</span><span class="p">)</span> <span class="p">[</span><span class="n">MSC</span> <span class="n">v</span><span class="o">.</span><span class="mi">1900</span> <span class="mi">64</span> <span class="n">bit</span> <span class="p">(</span><span class="n">AMD64</span><span class="p">)]</span> <span class="n">on</span> <span class="n">win32</span>
<span class="n">Type</span> <span class="s2">&quot;help&quot;</span><span class="p">,</span> <span class="s2">&quot;copyright&quot;</span><span class="p">,</span> <span class="s2">&quot;credits&quot;</span> <span class="ow">or</span> <span class="s2">&quot;license&quot;</span> <span class="k">for</span> <span class="n">more</span> <span class="n">information</span><span class="o">.</span>
<span class="p">(</span><span class="n">InteractiveConsole</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="kn">from</span> <span class="nn">polls.models</span> <span class="kn">import</span> <span class="n">Question</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice_text</span><span class="o">=</span><span class="s1">&#39;Not much&#39;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">Choice</span> <span class="nb">object</span><span class="o">&gt;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice_text</span><span class="o">=</span><span class="s1">&#39;The sky&#39;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">Choice</span> <span class="nb">object</span><span class="o">&gt;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice_text</span><span class="o">=</span><span class="s1">&#39;Just hacking again&#39;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="o">&lt;</span><span class="n">Choice</span><span class="p">:</span> <span class="n">Choice</span> <span class="nb">object</span><span class="o">&gt;</span>
</pre></div>


<p>为了方便大家，我将当前状态下的各主要文件内容一并贴出，供大家对照参考！</p>
<p>1--完整的<code>mysite/urls.py</code>文件如下：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span><span class="p">,</span><span class="n">include</span>
<span class="kn">from</span> <span class="nn">django.contrib</span> <span class="kn">import</span> <span class="n">admin</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^admin/&#39;</span><span class="p">,</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">urls</span><span class="p">),</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^polls/&#39;</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s1">&#39;polls.urls&#39;</span><span class="p">)),</span>
<span class="p">]</span>
</pre></div>


<p>2--完整的<code>mysite/settings.py</code>文件如下：</p>
<div class="codehilite"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>

<span class="c1"># Build paths inside the project like this: os.path.join(BASE_DIR, ...)</span>
<span class="n">BASE_DIR</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">abspath</span><span class="p">(</span><span class="vm">__file__</span><span class="p">)))</span>


<span class="c1"># Quick-start development settings - unsuitable for production</span>
<span class="c1"># See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/</span>

<span class="c1"># SECURITY WARNING: keep the secret key used in production secret!</span>
<span class="n">SECRET_KEY</span> <span class="o">=</span> <span class="s1">&#39;85vvuta(p05ow!4pz2b0qbduu0%pq6x5q66-ei*pg+-lbdr#m^&#39;</span>

<span class="c1"># SECURITY WARNING: don&#39;t run with debug turned on in production!</span>
<span class="n">DEBUG</span> <span class="o">=</span> <span class="bp">True</span>

<span class="n">ALLOWED_HOSTS</span> <span class="o">=</span> <span class="p">[]</span>


<span class="c1"># Application definition</span>

<span class="n">INSTALLED_APPS</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;polls&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.admin&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.auth&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.contenttypes&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.sessions&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.messages&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.staticfiles&#39;</span><span class="p">,</span>
<span class="p">]</span>

<span class="n">MIDDLEWARE</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;django.middleware.security.SecurityMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.sessions.middleware.SessionMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.middleware.common.CommonMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.middleware.csrf.CsrfViewMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.contrib.messages.middleware.MessageMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;</span><span class="p">,</span>
<span class="p">]</span>

<span class="n">ROOT_URLCONF</span> <span class="o">=</span> <span class="s1">&#39;mysite.urls&#39;</span>

<span class="n">TEMPLATES</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.template.backends.django.DjangoTemplates&#39;</span><span class="p">,</span>
        <span class="s1">&#39;DIRS&#39;</span><span class="p">:</span> <span class="p">[</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">BASE_DIR</span><span class="p">,</span> <span class="s1">&#39;templates&#39;</span><span class="p">)]</span>
        <span class="p">,</span>
        <span class="s1">&#39;APP_DIRS&#39;</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
        <span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;context_processors&#39;</span><span class="p">:</span> <span class="p">[</span>
                <span class="s1">&#39;django.template.context_processors.debug&#39;</span><span class="p">,</span>
                <span class="s1">&#39;django.template.context_processors.request&#39;</span><span class="p">,</span>
                <span class="s1">&#39;django.contrib.auth.context_processors.auth&#39;</span><span class="p">,</span>
                <span class="s1">&#39;django.contrib.messages.context_processors.messages&#39;</span><span class="p">,</span>
            <span class="p">],</span>
        <span class="p">},</span>
    <span class="p">},</span>
<span class="p">]</span>

<span class="n">WSGI_APPLICATION</span> <span class="o">=</span> <span class="s1">&#39;mysite.wsgi.application&#39;</span>


<span class="c1"># Database</span>
<span class="c1"># https://docs.djangoproject.com/en/1.11/ref/settings/#databases</span>

<span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s1">&#39;django.db.backends.sqlite3&#39;</span><span class="p">,</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">BASE_DIR</span><span class="p">,</span> <span class="s1">&#39;db.sqlite3&#39;</span><span class="p">),</span>
    <span class="p">}</span>
<span class="p">}</span>


<span class="c1"># Password validation</span>
<span class="c1"># https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators</span>

<span class="n">AUTH_PASSWORD_VALIDATORS</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">{</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;django.contrib.auth.password_validation.UserAttributeSimilarityValidator&#39;</span><span class="p">,</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;django.contrib.auth.password_validation.MinimumLengthValidator&#39;</span><span class="p">,</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;django.contrib.auth.password_validation.CommonPasswordValidator&#39;</span><span class="p">,</span>
    <span class="p">},</span>
    <span class="p">{</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;django.contrib.auth.password_validation.NumericPasswordValidator&#39;</span><span class="p">,</span>
    <span class="p">},</span>
<span class="p">]</span>


<span class="c1"># Internationalization</span>
<span class="c1"># https://docs.djangoproject.com/en/1.11/topics/i18n/</span>

<span class="n">LANGUAGE_CODE</span> <span class="o">=</span> <span class="s1">&#39;en-us&#39;</span>

<span class="n">TIME_ZONE</span> <span class="o">=</span> <span class="s1">&#39;Asia/Shanghai&#39;</span>

<span class="n">USE_I18N</span> <span class="o">=</span> <span class="bp">True</span>

<span class="n">USE_L10N</span> <span class="o">=</span> <span class="bp">True</span>

<span class="n">USE_TZ</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>


<p>3--完整的<code>polls/views.py</code>应该如下所示：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">reverse</span>
<span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">HttpResponseRedirect</span>
<span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">get_object_or_404</span>
<span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Choice</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Question</span>
<span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">loader</span>
<span class="c1"># Create your views here.</span>


<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">latest_question_list</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;-pub_date&#39;</span><span class="p">)[:</span><span class="mi">5</span><span class="p">]</span>
    <span class="n">template</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="s1">&#39;polls/index.html&#39;</span><span class="p">)</span>
    <span class="n">context</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s1">&#39;latest_question_list&#39;</span><span class="p">:</span> <span class="n">latest_question_list</span><span class="p">,</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">request</span><span class="p">))</span>


<span class="k">def</span> <span class="nf">detail</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">question_id</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/detail.html&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;question&#39;</span><span class="p">:</span> <span class="n">question</span><span class="p">})</span>


<span class="k">def</span> <span class="nf">results</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">question_id</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/results.html&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;question&#39;</span><span class="p">:</span> <span class="n">question</span><span class="p">})</span>


<span class="k">def</span> <span class="nf">vote</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">question_id</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">selected_choice</span> <span class="o">=</span> <span class="n">question</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s1">&#39;choice&#39;</span><span class="p">])</span>
    <span class="k">except</span> <span class="p">(</span><span class="ne">KeyError</span><span class="p">,</span> <span class="n">Choice</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/detail.html&#39;</span><span class="p">,</span> <span class="p">{</span>
            <span class="s1">&#39;question&#39;</span><span class="p">:</span> <span class="n">question</span><span class="p">,</span>
            <span class="s1">&#39;error_message&#39;</span><span class="p">:</span> <span class="s2">&quot;You didn&#39;t select a choice.&quot;</span><span class="p">,</span>
        <span class="p">})</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">selected_choice</span><span class="o">.</span><span class="n">votes</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="n">selected_choice</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">HttpResponseRedirect</span><span class="p">(</span><span class="n">reverse</span><span class="p">(</span><span class="s1">&#39;polls:results&#39;</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">question</span><span class="o">.</span><span class="n">id</span><span class="p">,)))</span>
</pre></div>


<p>4--完整的<code>polls/urls.py</code>应该如下所示：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">views</span>

<span class="n">app_name</span> <span class="o">=</span> <span class="s1">&#39;polls&#39;</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="c1"># ex: /polls/</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">index</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;index&#39;</span><span class="p">),</span>
    <span class="c1"># ex: /polls/5/</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">detail</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;detail&#39;</span><span class="p">),</span>
    <span class="c1"># ex: /polls/5/results/</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/results/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">results</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;results&#39;</span><span class="p">),</span>
    <span class="c1"># ex: /polls/5/vote/</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/vote/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">vote</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;vote&#39;</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>


<p>5--完整的<code>polls/model.py</code>文件如下：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">import</span> <span class="nn">datetime</span>
<span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>
<span class="c1"># Create your models here.</span>

<span class="k">class</span> <span class="nc">Question</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">question_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">pub_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="s1">&#39;date published&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">was_published_recently</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">pub_date</span> <span class="o">&gt;=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">()</span> <span class="o">-</span> <span class="n">datetime</span><span class="o">.</span><span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">question_text</span>



<span class="k">class</span> <span class="nc">Choice</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">choice_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">votes</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>

    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">choice_text</span>
</pre></div>


<p>6--完整的<code>polls/admin.py</code>文件如下：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib</span> <span class="kn">import</span> <span class="n">admin</span>

<span class="c1"># Register your models here.</span>

<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Question</span>

<span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Question</span><span class="p">)</span>
</pre></div>


<p>7--完整的<code>templates/polls/index.html</code>文件如下：</p>
<div class="codehilite"><pre><span></span>{% if latest_question_list %}
    <span class="p">&lt;</span><span class="nt">ul</span><span class="p">&gt;</span>
    {% for question in latest_question_list %}
        <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">a</span> <span class="na">href</span><span class="o">=</span><span class="s">&quot;/polls/{{ question.id }}/&quot;</span><span class="p">&gt;</span>{{ question.question_text }}<span class="p">&lt;/</span><span class="nt">a</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
    {% endfor %}
    <span class="p">&lt;/</span><span class="nt">ul</span><span class="p">&gt;</span>
{% else %}
    <span class="p">&lt;</span><span class="nt">p</span><span class="p">&gt;</span>No polls are available.<span class="p">&lt;/</span><span class="nt">p</span><span class="p">&gt;</span>
{% endif %}
</pre></div>


<p>8--完整的<code>templates/polls/detail.html</code>文件如下：</p>
<div class="codehilite"><pre><span></span><span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>{{ question.question_text }}<span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;</span>

{% if error_message %}<span class="p">&lt;</span><span class="nt">p</span><span class="p">&gt;&lt;</span><span class="nt">strong</span><span class="p">&gt;</span>{{ error_message }}<span class="p">&lt;/</span><span class="nt">strong</span><span class="p">&gt;&lt;/</span><span class="nt">p</span><span class="p">&gt;</span>{% endif %}

<span class="p">&lt;</span><span class="nt">form</span> <span class="na">action</span><span class="o">=</span><span class="s">&quot;{% url &#39;polls:vote&#39; question.id %}&quot;</span> <span class="na">method</span><span class="o">=</span><span class="s">&quot;post&quot;</span><span class="p">&gt;</span>
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <span class="p">&lt;</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">&quot;radio&quot;</span> <span class="na">name</span><span class="o">=</span><span class="s">&quot;choice&quot;</span> <span class="na">id</span><span class="o">=</span><span class="s">&quot;choice{{ forloop.counter }}&quot;</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;{{ choice.id }}&quot;</span> <span class="p">/&gt;</span>
    <span class="p">&lt;</span><span class="nt">label</span> <span class="na">for</span><span class="o">=</span><span class="s">&quot;choice{{ forloop.counter }}&quot;</span><span class="p">&gt;</span>{{ choice.choice_text }}<span class="p">&lt;/</span><span class="nt">label</span><span class="p">&gt;&lt;</span><span class="nt">br</span> <span class="p">/&gt;</span>
{% endfor %}
<span class="p">&lt;</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">&quot;submit&quot;</span> <span class="na">value</span><span class="o">=</span><span class="s">&quot;Vote&quot;</span> <span class="p">/&gt;</span>
<span class="p">&lt;/</span><span class="nt">form</span><span class="p">&gt;</span>
</pre></div>


<p>9--完整的<code>templates/polls/results.html</code>文件如下：</p>
<div class="codehilite"><pre><span></span><span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>{{ question.question_text }}<span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">ul</span><span class="p">&gt;</span>
{% for choice in question.choice_set.all %}
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;</span>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}<span class="p">&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
{% endfor %}
<span class="p">&lt;/</span><span class="nt">ul</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">a</span> <span class="na">href</span><span class="o">=</span><span class="s">&quot;{% url &#39;polls:detail&#39; question.id %}&quot;</span><span class="p">&gt;</span>Vote again?<span class="p">&lt;/</span><span class="nt">a</span><span class="p">&gt;</span>
</pre></div>


<p>vote()视图没有对应的html模板，它直接跳转到results视图去了。</p>
<p>运行服务器，测试各功能：</p>
<p>这是问卷列表页面：</p>
<p><img alt="image.png-13kB" src="http://static.zybuluo.com/feixuelove1009/7pdy5vvn8to2ntg7w46ker09/image.png" /></p>
<p>这是“what's up”问卷选项页面：</p>
<p><img alt="image.png-23.9kB" src="http://static.zybuluo.com/feixuelove1009/ph5kz2fspfjpn287tci35dg8/image.png" /></p>
<p>这是选择结果页面：</p>
<p><img alt="image.png-26.2kB" src="http://static.zybuluo.com/feixuelove1009/y09ovdw2cibwair93z8hrwht/image.png" /></p>
<p>这是没有选择选项时，提示错误信息的页面：</p>
<p><img alt="image.png-28.4kB" src="http://static.zybuluo.com/feixuelove1009/4zdzz8lndebmgegi30fj9nf3/image.png" /></p>
<p>请大家对比参考上面的内容，看看你自己的结果是否一样。</p>
<h2 id="_1">二、 使用类视图：减少重复代码</h2>
<p>上面的detail、index和results视图的代码非常相似，有点冗余，这是一个程序猿不能忍受的。他们都具有类似的业务逻辑，实现类似的功能：通过从URL传递过来的参数去数据库查询数据，加载一个模板，利用刚才的数据渲染模板，返回这个模板。由于这个过程是如此的常见，Django很善解人意的帮你想办法偷懒，于是它提供了一种快捷方式，名为“类视图”。</p>
<p>现在，让我们来试试看将原来的代码改为使用类视图的方式，整个过程分三步走：</p>
<ul>
<li>修改URLconf设置</li>
<li>删除一些旧的无用的视图</li>
<li>采用基于类视图的新视图</li>
</ul>
<p><strong>PS：为什么本教程的代码来回改动这么频繁？</strong></p>
<p>答：通常在写一个Django的app时，我们一开始就要决定使用类视图还是不用，而不是等到代码写到一半了才重构你的代码成类视图。但是本教程为了让你清晰的理解视图的内涵，“故意”走了一条比较曲折的路，因为我们的哲学是<code>在你使用计算器之前你得先知道基本的数学公式</code>。</p>
<h3 id="1urlconf">1.<strong>改良URLconf</strong></h3>
<p>打开<code>polls/urls.py</code>文件，将其修改成下面的样子：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">views</span>

<span class="n">app_name</span> <span class="o">=</span> <span class="s1">&#39;polls&#39;</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">IndexView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;index&#39;</span><span class="p">),</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;pk&gt;[0-9]+)/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">DetailView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;detail&#39;</span><span class="p">),</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;pk&gt;[0-9]+)/results/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">ResultsView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;results&#39;</span><span class="p">),</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/vote/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">vote</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;vote&#39;</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>


<p>请注意：在上面的的第2,3条目中将原来的<code>&lt;question_id&gt;</code>修改成了<code>&lt;pk&gt;</code>.</p>
<h3 id="2">2.<strong>修改视图</strong></h3>
<p>接下来，打开<code>polls/views.py</code>文件，删掉index、detail和results视图，替换成Django的类视图，如下所示：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">get_object_or_404</span><span class="p">,</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponseRedirect</span>
<span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">reverse</span>
<span class="kn">from</span> <span class="nn">django.views</span> <span class="kn">import</span> <span class="n">generic</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Choice</span><span class="p">,</span> <span class="n">Question</span>


<span class="k">class</span> <span class="nc">IndexView</span><span class="p">(</span><span class="n">generic</span><span class="o">.</span><span class="n">ListView</span><span class="p">):</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;polls/index.html&#39;</span>
    <span class="n">context_object_name</span> <span class="o">=</span> <span class="s1">&#39;latest_question_list&#39;</span>
    <span class="k">def</span> <span class="nf">get_queryset</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;返回最近发布的5个问卷.&quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;-pub_date&#39;</span><span class="p">)[:</span><span class="mi">5</span><span class="p">]</span>


<span class="k">class</span> <span class="nc">DetailView</span><span class="p">(</span><span class="n">generic</span><span class="o">.</span><span class="n">DetailView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Question</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;polls/detail.html&#39;</span>


<span class="k">class</span> <span class="nc">ResultsView</span><span class="p">(</span><span class="n">generic</span><span class="o">.</span><span class="n">DetailView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Question</span>
    <span class="n">template_name</span> <span class="o">=</span><span class="s1">&#39;polls/results.html&#39;</span>


<span class="k">def</span> <span class="nf">vote</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
<span class="o">...</span> <span class="c1"># 这个视图未改变！！！</span>
</pre></div>


<p>在这里，我们使用了两种类视图<code>ListView</code>和<code>DetailView</code>（它们是作为父类被继承的）。这两者分别代表“显示一个对象的列表”和“显示特定类型对象的详细页面”的抽象概念。</p>
<ul>
<li>
<p>每一种类视图都需要知道它要作用在哪个模型上，这通过model属性提供。</p>
</li>
<li>
<p><code>DetailView</code>类视图需要从url捕获到的称为"pk"的主键值，因此我们在url文件中将2和3条目的<code>&lt;question_id&gt;</code>修改成了<code>&lt;pk&gt;</code>。</p>
</li>
</ul>
<p>默认情况下，<code>DetailView</code>类视图使用一个称作<code>&lt;app name&gt;/&lt;model name&gt;_detail.html</code>的模板。在本例中，实际使用的是<code>polls/detail.html</code>。<code>template_name</code>属性就是用来指定这个模板名的，用于代替自动生成的默认模板名。（一定要仔细观察上面的代码，对号入座，注意细节。）同样的，在resutls列表视图中，指定<code>template_name</code>为<code>'polls/results.html'</code>，这样就确保了虽然resulst视图和detail视图同样继承了DetailView类，使用了同样的model：Qeustion，但它们依然会显示不同的页面。（模板不同嘛！so easy！）</p>
<p>类似的，ListView类视图使用一个默认模板称为<code>&lt;app name&gt;/&lt;model name&gt;_list.html</code>。我们也使用<code>template_name</code>这个变量来告诉ListView使用我们已经存在的
<code>"polls/index.html"</code>模板，而不是使用它自己默认的那个。</p>
<p>在教程的前面部分，我们给模板提供了一个包含<code>question</code>和<code>latest_question_list</code>的上下文变量。而对于DetailView，question变量会被自动提供，因为我们使用了Django的模型（Question），Django会智能的选择合适的上下文变量。然而，对于ListView，自动生成的上下文变量是<code>question_list</code>。为了覆盖它，我们提供了<code>context_object_name</code>属性，指定说我们希望使用<code>latest_question_list</code>而不是<code>question_list</code>。</p>
<p>现在可以运行开发服务器，然后试试基于类视图的应用程序了。类视图是Django比较高级的一种用法，初学可能不太好理解，没关系，我们先有个印象。</p>
            </div>
            <!-- 教程正文主体部分结束 -->

            <hr />


            <!-- 打赏部分开始 -->

















            <!-- 打赏部分结束 -->


            <!-- 教程导航条 -->
            <div class="row">
                
                    <a class="pull-left" href="89.html">
                        <i class="glyphicon glyphicon-chevron-left"></i>Part 3：视图和模板</a>
                

                
                    <a class="pull-right" href="91.html">
                        Part 5：测试<i class="glyphicon glyphicon-chevron-right"></i></a>
                
            </div>
            <!-- 教程导航条结束 -->


            <hr />

            <!-- 评论区-->
            

            <!-- 显示评论条数-->
            <div class="row">
                
                <h3>评论总数：  15</h3>
                <hr />
            </div>

            <!-- 评论表单区-->
            <div class="row">
                
                
                <a href="90.html">登录后方可评论</a>
                
            </div>
            <!-- 评论表单区结束-->

            <hr />

            <!-- 评论显示区-->
            <div class="row">
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tvax4.sinaimg.cn/default/images/default_avatar_male_50.gif" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >启动服务报错</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    吃瓜群众一份子
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年3月7日 23:35</em>
                                        <a href="/reply/253">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>polls/views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from .models import Choice, Question

def vote(request,question_id):
    # return HttpResponse(&quot;You are voting for question %s.&quot;% question_id)
    question=get_object_or_404(Question,pk=question_id)
    try:
        selected_choice=question.choice_set.get(pk=request.POST[&#39;choice&#39;])
    except (KeyError,Choice.DoesNotExist):
        return render(request,&quot;polls/detail.html&quot;,{
            &#39;question&#39;:question,
            &#39;error_message&#39;:&quot;You don&#39;t select a choice.&quot;,
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse(&#39;polls:results&#39;,args=(question.id,)))

class IndexView(generic.ListView):
    template_name = &#39;polls/index.html&#39;
    context_object_name = &#39;latest_question_list&#39;
    def get_queryset(self):
        return Question.objects.order_by(&#39;-pub_date&#39;)[:5]

class DetailView(generic.DetailView):
    model=Question
    template_name = &#39;polls/detail.html&#39;

class ResultView(generic.DetailView):
    model = Question
    template_name = &#39;polls/results.html&#39;
报错：
Traceback (most recent call last):
  File &quot;D:/Python/study/mysite/polls/views.py&quot;, line 5, in &lt;module&gt;
    from .models import Choice, Question
ModuleNotFoundError: No module named &#39;__main__.models&#39;; &#39;__main__&#39; is not a package</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax4.sinaimg.cn/default/images/default_avatar_male_50.gif" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >看错了</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    吃瓜群众一份子
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    吃瓜群众一份子
                                                
                                            </span>
                                        
                                        <em>2018年3月7日 23:44</em>
                                        <a href="/reply/254">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>这个是我自己打开方式不对，不好意思.....</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.180.180.50/c2263662jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >return报错</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    俺是BB
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年2月2日 16:12</em>
                                        <a href="/reply/184">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>class IndexView(generic.ListView):
    template_name = &#39;polls/index.html&#39;
    context_object_name = &#39;latest_question_list&#39;
    def get_queryset(self):
    &quot;&quot;&quot;返回最近发布的5个问卷.&quot;&quot;&quot;
        return Question.objects.order_by(&#39;-pub_date&#39;)[:5]

这里的return，我这边报错，说out of function，怎么办啊，哇呜</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.80.80.50/0065sTQcjw8eqpbxtxeq1j3028028q2p.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >笔记</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    ywhyme
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年1月25日 11:55</em>
                                        <a href="/reply/156">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>get_object_or_404(klass,, pk=question_id)
 klass   may be a Model, Manager, or QuerySet object. All other passed
    arguments and keyword arguments are used in the get() query.
pk是id的意思,当然也可写成id = question_id,或者写成question_text=&quot;你想查询的question_text&quot;</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.80.80.50/0065sTQcjw8eqpbxtxeq1j3028028q2p.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >GET</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    ywhyme
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    ywhyme
                                                
                                            </span>
                                        
                                        <em>2018年1月25日 12:06</em>
                                        <a href="/reply/157">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>get() 为queryset下的get方法</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tvax4.sinaimg.cn/crop.11.0.1103.1103.50/bff4b132ly8fk9nlj1x56j20v90ungne.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >谢谢刘老师</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    安思危_Amur
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年1月3日 22:59</em>
                                        <a href="/reply/107">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>谢谢刘老师</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.426.66.1066.1066.50/005EMUrrly8flohkwuo2uj31hc0xce81.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >问下</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    wenlei890929
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年12月13日 17:54</em>
                                        <a href="/reply/87">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>vote{{ choice.votes|pluralize }} 啥意思</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >复数形式</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    wenlei890929
                                                
                                            </span>
                                        
                                        <em>2017年12月13日 20:20</em>
                                        <a href="/reply/88">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>我们知道英文中的名词分复数和单数形式，比如apple和apples。
pluralize是Django内置的一个过滤器，当choice.votes这个变量的值大于1时，也就是复数时，就在字符串vote后面加个s。如果值是1，也就是单数形式，就不加s。

Django很细对吧？这么小的细节都考虑到了！</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 8em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.426.66.1066.1066.50/005EMUrrly8flohkwuo2uj31hc0xce81.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >谢谢</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    wenlei890929
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                            </span>
                                        
                                        <em>2017年12月14日 14:01</em>
                                        <a href="/reply/89">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>考虑很详细，讲解很详细</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tvax4.sinaimg.cn/crop.13.0.723.723.50/005GkKe9ly8fkxegjen9ij30ku0k3jtr.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >请教一个问题</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    PhingRczhx
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年11月23日 19:34</em>
                                        <a href="/reply/56">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>我在点击vote的时候出现    _reverse_with_prefix() argument after * must be an iterable, not int 错误</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >仔细核对一下代码吧</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    PhingRczhx
                                                
                                            </span>
                                        
                                        <em>2017年11月23日 19:45</em>
                                        <a href="/reply/58">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>确保是完全按照教程进行的。</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tvax4.sinaimg.cn/crop.13.0.723.723.50/005GkKe9ly8fkxegjen9ij30ku0k3jtr.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >很不错的文章，发现一个小问题</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    PhingRczhx
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年11月23日 18:12</em>
                                        <a href="/reply/54">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>在detail.html中，form表单的action的url是不是写错了，改成&quot;{% url &#39;polls:results&#39; question.id %}
不过不影响 细心的人应该都会看出来。</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax4.sinaimg.cn/crop.13.0.723.723.50/005GkKe9ly8fkxegjen9ij30ku0k3jtr.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >，</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    PhingRczhx
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    PhingRczhx
                                                
                                            </span>
                                        
                                        <em>2017年11月23日 19:25</em>
                                        <a href="/reply/55">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>不好意我理解错了，看错了</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >没错</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    PhingRczhx
                                                
                                            </span>
                                        
                                        <em>2017年11月23日 19:41</em>
                                        <a href="/reply/57">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>你再仔细看一下。</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva1.sinaimg.cn/crop.0.0.180.180.50/c2dc2d09jw1fe1nwdyb2uj2050050wea.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >深入浅出，浅显易懂</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    svcasvawe
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年11月17日 16:05</em>
                                        <a href="/reply/41">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>深入浅出，浅显易懂</p>
                        </div>
                    </div>
                
            </div>
            <!-- 评论显示区结束-->

            <!-- 评论区结束-->

        </div>
        <!-- 右侧正文栏结束 -->

      </div>
    </div>




    <div id="back-to-top" >
        <span class="glyphicon glyphicon-arrow-up"></span>
    </div>


    <footer id="footer" class="midnight-blue">
        <div class="container-fluid" style="font-size: smaller">
            <div class="row footer-1">
                <div class="col-md-2">
                    Copyright &copy; 2018.刘江的官方网站
                </div>
                <div class="col-md-3">
                    托管于<a target="_blank" href="https://www.aliyun.com/">阿里云</a>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <a target="_blank" href="http://www.miitbeian.gov.cn/">京ICP备17055098号</a>
                </div>
                <div class="col-md-2">
                    <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010602120033">

                        <span><img style="display: inline;margin: 0 auto;" src="/static/images/ghs.png" />京公网安备11010102002019号</span>
                    </a>
                </div>
                <div class="col-md-5">
                    <ul class="pull-right">
                        <li><a href="/blog/">返回首页</a></li>
                        <li><a href="/about/">关于博主</a></li>
                        <li><a href="#">常见问题</a></li>
                        <li><a href="/contact/" target="_blank">广告合作</a></li>
                        <li><a href="/contact/" target="_blank">联系方式</a></li>
                        <li><a href="#">使用许可</a></li>
                    </ul>
                </div>
            </div>







        </div>
    </footer><!--/#footer-->

    <script src="/static/js/jquery.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>


    <script>


        //为新闻添加访问量
        function count_visiting(news_id){
            var to_url = "/news/visiting/"+news_id;
            jQuery.get(to_url);
        }


        $("#donate").click(function () {
            $("#donate_page").toggleClass('hidden');
        });



        <!-- 导航条对应条目active -->
        $(document).ready(function () {

            $('.navbar-nav').find('a').each(function () {
                if (this.href == document.location.href || document.location.href.search(this.href) >= 0) {
                    $(this).parent().addClass('active'); // this.parent.className = 'active';
                }
            });

            $('table').addClass('table table-bordered table-hover');

            $('img').addClass('img-responsive');

            $('#back-to-top').click(function () {
                window.scrollTo(0,0);
            });

        });

    

        $('button.navbar-toggle').click(function () {
            $('#my-navbar').css("background","#337ab7")
        });
        
    </script>

</body>

</html>